package com.v1.video.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.json.JSONException;

import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.iss.view.common.ToastAlone;
import com.v1.video.AppContext;
import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.domain.BaseInfo;
import com.v1.video.domain.BindInfo;
import com.v1.video.domain.IsEditUserNameInfo;
import com.v1.video.domain.LoginInfo;
import com.v1.video.domain.SetHead;
import com.v1.video.engine.NetEngine;
import com.v1.video.engine.RequestEngine;
import com.v1.video.exception.NetException;
import com.v1.video.util.ImageFileCache;
import com.v1.video.util.Logger;
import com.v1.video.util.Utility;
import com.v1.video.util.Utils;
import com.v1.video.widgets.MyDialog;

public class PersonInfoActivity extends BaseActivity implements OnClickListener {

	private static final String TAG = "PersonInfoActivity";
	private final static int REQUEST_CODE_PHOTO_SUMSUNG = 100;

	private PersonInfoActivity instance;

	// setText(Html.fromHtml("<u>"+"hahaha"+"</u>"));
	// id="1";

	/** 标题 */
	TextView text_title;
	TextView txtReturn = null;

	/** 返回按钮 */
	private ImageView view_btn_return;

	/** 头像背景 */
	private RelativeLayout layout_headimg = null;
	/** 个人中心的上面的四方背景 */
	private RelativeLayout layout_backImg = null;

	/** 昵称 */
	private RelativeLayout layout_nickname = null;
	private TextView text_nickName;

	/** 用户名 */
	private RelativeLayout layout_username = null;
	private TextView text_userName;

	/** 性别 */
	private RelativeLayout layout_sex = null;

	/** 性别名称 */
	private TextView txt_sex = null;
	private ImageView imgSex = null;

	/** 性别变量：0表示保密 ，1表示男，2表示女； */
	private int userSex = 0;

	/** 个性签名 */
	private RelativeLayout layout_sign = null;

	/** 地区 */
//	private RelativeLayout layout_area = null;

	/** 地区的名称 */
//	private TextView txt_area = null;

	/** 注销当前账号 */
	private RelativeLayout layout_closeAccount = null;

	private MyDialog dialogCommon;

	/** 头像 */
	private ImageView viewHead = null;

	// /** 地区的展示 */
	// private ShopWheelViewDialog dialogArea;

	// /** 获取地区的数据 */
	// private GetDataTask mTask;

	public static final int STATE_PAIZHAO = 101;// 拍照

	public static final int STATE_ALBUM = 102;// 相册

	private final int STATE_CAIJIAN = 103;// 裁剪

	private final int HAND_HEAD = 201;// 头像

	private final int HAND_SEX = 202;// 性别

	private final int HAND_AREA = 203;// 地区
	private final int HAND_AREA_OK = 207;// 地区
	private final int HAND_AREA_FAIL = 208;// 地区

	private final int HAND_NICKNAME = 204;// 昵称

	private final int HAND_SIGN = 205;// 签名

	private final int HAND_PWD = 206;// 密码
	
	public static final int STATE_PAIZHAO_BACK = 210;// 背景拍照

	public static final int STATE_ALBUM_BACK = 211;// 背景相册

	private final int STATE_CAIJIAN_BACK = 212;// 背景裁剪

	private final int HAND_BACK = 213;// 背景
	
	private final int HAND_MODIFY_HEAD_SUCCESS = 214;
	private final int HAND_MODIFY_HEAD_FAIL = 215;
	private final int HAND_MODIFY_HEAD_TIMEOUT = 216;
	private final int HAND_MODIFY_BACK_SUCCESS = 217;
	private final int HAND_MODIFY_BACK_FAIL = 218;
	private final int HAND_MODIFY_BACK_TIMEOUT = 219;
	private final int HAND_MODIFY_STATE_HEAD = 220;
	private final int HAND_MODIFY_STATE_BACK = 221;

	private boolean isJudge = false;
//	private TextView txtNameModity = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_person_info);
		instance = this;

		if (savedInstanceState != null) {
			String demouri = savedInstanceState.getString("imageFileUri");
			if (!TextUtils.isEmpty(demouri)) {
				imageFileUri = Uri.parse(demouri);
			}
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		Logger.i(TAG, "onSaveInstanceState=============");
		if (imageFileUri != null) {
			outState.putString("imageFileUri", imageFileUri.toString());
		}
	}
	

	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		super.onNewIntent(intent);
		setIntent(intent);
		if (intent != null) {
			String demouri = intent.getStringExtra("imageFileUri");
			if (!TextUtils.isEmpty(demouri)) {
				imageFileUri = Uri.parse(demouri);
			}
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		text_title.setText(R.string.person_info_title);
//		txtReturn.setText("我");
		text_userName.setText(LoginInfo.getInstance().getUserName());
		text_nickName.setText(LoginInfo.getInstance().getNickName());
		txt_sex.setText(LoginInfo.getInstance().getSex());
		if(LoginInfo.getInstance().getSex().equals("女")){
			imgSex.setImageResource(R.drawable.icon_sex_woman);
		}else{
			imgSex.setImageResource(R.drawable.icon_sex_man);
		}
//		txt_area.setText(LoginInfo.getInstance().getRegion());
		setTextDetail(LoginInfo.getInstance().getDetail());

	}

	@Override
	protected void initView() {
		// TODO Auto-generated method stub

		view_btn_return = (ImageView) findViewById(R.id.iv_result);
		text_title = (TextView) findViewById(R.id.tv_title);

		layout_headimg = (RelativeLayout) findViewById(R.id.person_info_headimg_back);
		layout_nickname = (RelativeLayout) findViewById(R.id.person_info_nickname_back);
		layout_sex = (RelativeLayout) findViewById(R.id.person_info_sex_back);
		layout_sign = (RelativeLayout) findViewById(R.id.person_info_personality_sign);
//		layout_area = (RelativeLayout) findViewById(R.id.person_info_area_back);
		layout_closeAccount = (RelativeLayout) findViewById(R.id.person_info_cancel_account);
		layout_backImg = (RelativeLayout) findViewById(R.id.person_info_backimg_back);
		viewHead = (ImageView) findViewById(R.id.person_info_head_img);

		txt_sex = (TextView) findViewById(R.id.person_info_sex_name);
//		txt_area = (TextView) findViewById(R.id.person_info_area_name);
		txt_detail = (TextView) findViewById(R.id.person_info_personality_hint);
		text_nickName = (TextView) findViewById(R.id.person_info_nickname_name);

		layout_username = (RelativeLayout) findViewById(R.id.person_info_username_back);
		text_userName = (TextView) findViewById(R.id.person_info_username_name);
//		txtNameModity = (TextView) findViewById(R.id.person_info_username_modify);

		txtReturn = (TextView) findViewById(R.id.tv_result);
		imgSex = (ImageView)findViewById(R.id.person_info_sex_icon);
	}

	private ProgressDialog pd;

	@Override
	protected void initData() {
		// TODO Auto-generated method stub

//		if (isGoSetUserName()) {
//			if (pd == null) {
//				pd = createDialog(PersonInfoActivity.this, getResources()
//						.getString(R.string.get_data));
//				pd.show();
//			}
//			new SendDataAsync(0).execute();
//		}
		
		imgCacheUtil = new ImageFileCache();
		if (AppContext.getHeadBitmap() != null) {
			Logger.i(TAG, "此处设置头像执行了。。。。。。。");
			viewHead.setImageBitmap(Utils.toRoundBitmap(AppContext
					.getHeadBitmap()));
		} else {
			Logger.i(TAG, "此处设置头像执行了。。。。。。1111111111111");
			SetHead setHead = new SetHead();
			setHead.setHead(LoginInfo.getInstance().getUserImg(), LoginInfo
					.getInstance().getSex(), viewHead);
		}
		
	}
	
	private ProgressDialog createDialog(Context context, String message) {

		ProgressDialog pg = new ProgressDialog(context);
		pg.setMessage(message);
		pg.setCanceledOnTouchOutside(false);
		pg.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {

			}
		});
		pg.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode,
					KeyEvent event) {
				switch (keyCode) {
				case KeyEvent.KEYCODE_BACK:
					dialog.cancel();
				}
				return false;
			}
		});
		return pg;
	}

	@Override
	protected void setListener() {
		// TODO Auto-generated method stub
//		layout_area.setOnClickListener(this);
		layout_sex.setOnClickListener(this);
		layout_headimg.setOnClickListener(this);
		layout_sign.setOnClickListener(this);
		layout_nickname.setOnClickListener(this);
		layout_closeAccount.setOnClickListener(this);
		text_nickName.setOnClickListener(this);
		layout_backImg.setOnClickListener(this);
		layout_username.setOnClickListener(this);
		findViewById(R.id.lay_result).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
            	onBackPressed();
            }
        });
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		// if(LoginInfo.getInstance().getLoginState() ==
		// LoginInfo.THIRDPARTY_LOGIN &&
		// !LoginInfo.getInstance().getIsuser().isIseditusername() &&
		// !(v.getId() == R.id.person_info_cancel_account)){
		//
		// //第三方登录，判断是否设置用户名密码
		// Intent userNameIntent = new Intent();
		// userNameIntent.setClass(instance,SetUserNameActivity.class);
		// startActivity(userNameIntent);
		//
		// }else{

		switch (v.getId()) {
		case R.id.iv_result:
			onBackPressed();
			break;
//		case R.id.person_info_area_back:// 地区
//
////			if (isGoSetUserName()) {
////				if (!isJudge) {
////					if (pd == null) {
////						pd = createDialog(PersonInfoActivity.this,
////								getResources().getString(R.string.get_data));
////						pd.show();
////					}
////					new SendDataAsync(1).execute();
////					return;
////				}
////				goSetUsername();
////			} else {
//				areaSelectShow();
////			}
//			break;

		case R.id.person_info_sex_back:// 性别

//			if (isGoSetUserName()) {
//				if (!isJudge) {
//					if (pd == null) {
//						pd = createDialog(PersonInfoActivity.this,
//								getResources().getString(R.string.get_data));
//						pd.show();
//					}
//					new SendDataAsync(2).execute();
//					return;
//				}
//				goSetUsername();
//			} else {
				sexSelectShow();
//			}
			break;
		case R.id.person_info_headimg_back:

//			if (isGoSetUserName()) {
//				if (!isJudge) {
//					if (pd == null) {
//						pd = createDialog(PersonInfoActivity.this,
//								getResources().getString(R.string.get_data));
//						pd.show();
//					}
//					new SendDataAsync(3).execute();
//					return;
//				}
//				goSetUsername();
//			} else {
				headImgModify();
//			}
			break;
		case R.id.person_info_personality_sign:// 个性签名

//			if (isGoSetUserName()) {
//				if (!isJudge) {
//					if (pd == null) {
//						pd = createDialog(PersonInfoActivity.this,
//								getResources().getString(R.string.get_data));
//						pd.show();
//					}
//					new SendDataAsync(4).execute();
//					return;
//				}
//				goSetUsername();
//			} else {
				Intent intent = new Intent();
				intent.setClass(PersonInfoActivity.this,
						PersonSignActivity.class);
				startActivityForResult(intent, HAND_SIGN);
//			}
			break;
		case R.id.person_info_nickname_back:// 昵称
//			if (isGoSetUserName()) {
//				if (!isJudge) {
//					if (pd == null) {
//						pd = createDialog(PersonInfoActivity.this,
//								getResources().getString(R.string.get_data));
//						pd.show();
//					}
//					new SendDataAsync(7).execute();
//					return;
//				}
//				goSetUsername();
//			} else {
				Intent userNameIntent = new Intent();
				userNameIntent.setClass(instance,
						OptionModifyNickNameActivity.class);
				startActivityForResult(userNameIntent, HAND_NICKNAME);
//			}

			break;
		case R.id.person_info_username_back:// 用户名
//			if (isGoSetUserName()) {
//				if (!isJudge) {
//					if (pd == null) {
//						pd = createDialog(PersonInfoActivity.this,
//								getResources().getString(R.string.get_data));
//						pd.show();
//					}
//					new SendDataAsync(5).execute();
//					return;
//				}
//				goSetUsername();
//			}
			break;
		case R.id.person_info_backimg_back:// 背景图片
			Logger.i(TAG, "背景图片");
//			if (isGoSetUserName()) {
//				if (!isJudge) {
//					if (pd == null) {
//						pd = createDialog(PersonInfoActivity.this,
//								getResources().getString(R.string.get_data));
//						pd.show();
//					}
//					new SendDataAsync(8).execute();
//					return;
//				}
//				goSetUsername();
//			} else {
				backImgModify();
//			}
			
			break;
//		case R.id.person_info_pwd_back:// 密码安全
//
////			if (isGoSetUserName()) {
////				if (!isJudge) {
////					if (pd == null) {
////						pd = createDialog(PersonInfoActivity.this,
////								getResources().getString(R.string.get_data));
////						pd.show();
////					}
////					new SendDataAsync(6).execute();
////					return;
////				}
////				goSetUsername();
////			} else {
//				Intent intentPwd = new Intent();
//				intentPwd.setClass(PersonInfoActivity.this,
//						PersonPwdModifyActivity.class);
//				startActivity(intentPwd);
////			}
//			break;
		case R.id.person_info_cancel_account:
			closeAccountProcess();
			break;
		}

		// }

	}

	/** 是否已设置过用户名 */
	private boolean isGoSetUserName() {
		// Logger.i(TAG,
		// "LoginInfo.getInstance().getLoginState() == "+LoginInfo.getInstance().getLoginState());
		// if(LoginInfo.getInstance().isSetUserName()){
		// Logger.i(TAG, "LoginInfo.getInstance().isSetUserName() is true");
		// }else{
		// Logger.i(TAG, "LoginInfo.getInstance().isSetUserName() is false");
		// }
		// if(LoginInfo.getInstance().getLoginState() ==
		// LoginInfo.THIRDPARTY_LOGIN &&
		// !LoginInfo.getInstance().getIsuser().isIseditusername()){
		// if(!LoginInfo.getInstance().isSetUserName()){
		if (LoginInfo.getInstance().getLoginState() == LoginInfo.THIRDPARTY_LOGIN
				&& !LoginInfo.getInstance().isSetUserName()) {
			return true;
		} else {
			return false;
		}
	}

	private void goSetUsername() {
		Intent userNameIntent = new Intent();
		userNameIntent.setClass(instance, SetUserNameActivity.class);
		startActivity(userNameIntent);
	}

	/** 地区选择 */
	private void areaSelectShow() {
		// if (dialogArea != null) {
		// dialogArea.show();
		// } else {
		// dialogArea = new ShopWheelViewDialog(this);
		// mTask = new GetDataTask(this);
		// mTask.execute();
		// }

		// // Intent intent = new Intent(PersonInfoActivity.this,
		// LocationSelectActivity.class);
		// // startActivityForResult(intent, HAND_AREA);
		// Intent intent = new Intent(PersonInfoActivity.this,
		// CityChoiceActivity.class);
		// intent.putExtra("currentPosition", currentPosition);
		// startActivityForResult(intent, HAND_AREA);
		copyFile("city.db", PersonInfoActivity.this);
	}

	private void gotoCitySelect() {
		Intent intent = new Intent(PersonInfoActivity.this,
				CityChoiceActivity.class);
		startActivityForResult(intent, HAND_AREA);
	}

	private void copyFile(final String filename, final Context context) {
		final File file = new File(context.getFilesDir(), filename);
		if (file.exists() && file.length() > 0) {
			// 已经有了
			Logger.i("TAG", "数据库文件已经存在，不用拷贝");
			Message message = Message.obtain();
			message.what = HAND_AREA_OK;
			handler.sendMessage(message);
		} else {
			// 还没有
			new Thread() {
				public void run() {
					File destfile = copyFile(context, filename,
							file.getAbsolutePath());
					Message message = Message.obtain();
					if (destfile != null) {
						// 拷贝数据库成功
						message.what = HAND_AREA_OK;
					} else {
						// 拷贝失败
						message.what = HAND_AREA_FAIL;
					}
					handler.sendMessage(message);
				};
			}.start();
		}
	}

	public static File copyFile(Context context, String fileName, String dest) {
		try {
			InputStream is = context.getAssets().open(fileName);// 打开assets目录下的文件
			Logger.i(TAG, "dest==" + dest);
			File file = new File(dest);
			FileOutputStream fos = new FileOutputStream(file);
			byte[] b = new byte[1024];
			int len = -1;
			while ((len = is.read(b)) != -1) {
				fos.write(b, 0, len);

			}
			fos.close();
			is.close();
			return file;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

	}

	/** 注销账号 */
	private void closeAccountProcess() {
		final MyDialog dialog = Utility.createDialog(this,
				R.style.dialog_custom);
		((TextView) dialog.findViewById(R.id.tv_dialog_content))
				.setText("确定注销此帐号？");
		TextView cancel = (TextView) dialog.findViewById(R.id.tv_dialog_cancel);
		TextView ok = (TextView) dialog.findViewById(R.id.tv_dialog_ok);
		ok.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.dismiss();
				// 注销的时候需要清空用户保存的频道信息
				File file = new File(PersonInfoActivity.this.getFilesDir(),
						Constant.CHANNEL_FILENAME);
				if (file != null && file.exists()) {
					file.delete();
				}
				logout();
			}
		});
		cancel.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		dialog.show();
	}

//	ImageView btnSecret;
	ImageView btnBoy;
	ImageView btnGirl;

	/** 选择性别 */
	private void sexSelectShow() {

		if (dialogCommon != null) {
			dialogCommon = null;
		}

		//
		final MyDialog dialogCommon = new MyDialog(this,
				R.style.dialog_headsetting);
		LinearLayout linearlayout;
		android.view.WindowManager.LayoutParams layoutparams;
		linearlayout = (LinearLayout) ((LayoutInflater) this
				.getSystemService("layout_inflater")).inflate(
				R.layout.dialog_person_sex, null);
		linearlayout.setMinimumWidth(10000);

		layoutparams = dialogCommon.getWindow().getAttributes();
		layoutparams.x = 0;
		layoutparams.y = -1000;
		layoutparams.gravity = 80;
		dialogCommon.onWindowAttributesChanged(layoutparams);

		dialogCommon.setCanceledOnTouchOutside(true);
		dialogCommon.setContentView(linearlayout);

		//

		// dialogCommon = new MyDialog(this, R.style.dialog_person_head);
		// dialogCommon.setContentView(R.layout.dialog_person_sex);
		// dialogCommon.setCancelable(false);
		// dialogCommon.setCanceledOnTouchOutside(false);

		if (LoginInfo.getInstance().getSex() != null) {

			if (LoginInfo.getInstance().getSex().equals("男")) {
				userSex = 1;
			} else if (LoginInfo.getInstance().getSex().equals("女")) {
				userSex = 2;
			} else if (LoginInfo.getInstance().getSex().equals("保密")
					|| LoginInfo.getInstance().getSex().equals("")) {
//				userSex = 0;
				userSex = 1;
			}

		}

//		btnSecret = (ImageView) dialogCommon
//				.findViewById(R.id.dialog_sex_secret_btn);
		btnBoy = (ImageView) dialogCommon.findViewById(R.id.dialog_sex_boy_btn);
		btnGirl = (ImageView) dialogCommon
				.findViewById(R.id.dialog_sex_girl_btn);
		/*if (userSex == 0) {
			btnSecret.setImageResource(R.drawable.btn_select_on_option);
			btnBoy.setImageResource(R.drawable.btn_select_down_option);
			btnGirl.setImageResource(R.drawable.btn_select_down_option);
		} else*/ if (userSex == 1) {
//			btnSecret.setImageResource(R.drawable.btn_select_down_option);
			btnBoy.setImageResource(R.drawable.btn_select_on_option);
			btnGirl.setImageResource(R.drawable.btn_select_down_option);
		} else if (userSex == 2) {
//			btnSecret.setImageResource(R.drawable.btn_select_down_option);
			btnBoy.setImageResource(R.drawable.btn_select_down_option);
			btnGirl.setImageResource(R.drawable.btn_select_on_option);
		}
		dialogCommon.findViewById(R.id.dialog_sex_boy).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialogCommon.dismiss();
						txt_sex.setText(R.string.person_sex_boy);
						LoginInfo.getInstance().setSex("男");
						imgSex.setImageResource(R.drawable.icon_sex_man);
						userSex = 1;
//						udateUserInfoThread(detailStr, txt_sex.getText().toString(),
//								/*txt_area.getText().toString()*/"");
						RequestEngine engine = new RequestEngine();
						engine.updataUserInfo(PersonInfoActivity.this, "男", 1);
					}
				});
		dialogCommon.findViewById(R.id.dialog_sex_boy).setOnTouchListener(
				new OnTouchListener() {

					@Override
					public boolean onTouch(View arg0, MotionEvent arg1) {
						// TODO Auto-generated method stub
//						btnSecret
//								.setImageResource(R.drawable.btn_select_down_option);
						btnBoy.setImageResource(R.drawable.btn_select_on_option);
						btnGirl.setImageResource(R.drawable.btn_select_down_option);
						
						return false;
					}
				});
		dialogCommon.findViewById(R.id.dialog_sex_girl).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialogCommon.dismiss();
						txt_sex.setText(R.string.person_sex_girl);
						LoginInfo.getInstance().setSex("女");
						imgSex.setImageResource(R.drawable.icon_sex_woman);
						userSex = 2;
//						udateUserInfoThread(detailStr, txt_sex.getText().toString(),
//								/*txt_area.getText().toString()*/"");
						RequestEngine engine = new RequestEngine();
						engine.updataUserInfo(PersonInfoActivity.this, "女", 1);
					}
				});
		dialogCommon.findViewById(R.id.dialog_sex_girl).setOnTouchListener(
				new OnTouchListener() {

					@Override
					public boolean onTouch(View arg0, MotionEvent arg1) {
						// TODO Auto-generated method stub
						// dialogCommon.dismiss();
						// txt_sex.setText(R.string.person_sex_girl);
						// userSex = 2;
//						btnSecret
//								.setImageResource(R.drawable.btn_select_down_option);
						btnBoy.setImageResource(R.drawable.btn_select_down_option);
						btnGirl.setImageResource(R.drawable.btn_select_on_option);
						return false;
					}
				});
//		dialogCommon.findViewById(R.id.dialog_sex_secret).setOnClickListener(
//				new OnClickListener() {
//
//					@Override
//					public void onClick(View v) {
//						dialogCommon.dismiss();
//						txt_sex.setText(R.string.person_sex_secret);
//						LoginInfo.getInstance().setSex("保密");
//						userSex = 0;
//						udateUserInfoThread(detailStr, txt_sex.getText().toString(),
//								txt_area.getText().toString());
//					}
//				});
//		dialogCommon.findViewById(R.id.dialog_sex_secret).setOnTouchListener(
//				new OnTouchListener() {
//
//					@Override
//					public boolean onTouch(View arg0, MotionEvent arg1) {
//						// TODO Auto-generated method stub
//						// dialogCommon.dismiss();
//						// txt_sex.setText(R.string.person_sex_secret);
//						// userSex = 0;
//						btnSecret
//								.setImageResource(R.drawable.btn_select_on_option);
//						btnBoy.setImageResource(R.drawable.btn_select_down_option);
//						btnGirl.setImageResource(R.drawable.btn_select_down_option);
//						return false;
//					}
//				});
		dialogCommon.findViewById(R.id.dialog_sex_cancel).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialogCommon.dismiss();
					}
				});
		dialogCommon.show();
	}

	private Uri imageFileUri = null;

	private void backImgModify() {

		if (dialogCommon != null) {
			dialogCommon = null;
		}

		final MyDialog dialogCommon = new MyDialog(this,
				R.style.dialog_headsetting);
		LinearLayout linearlayout;
		android.view.WindowManager.LayoutParams layoutparams;
		linearlayout = (LinearLayout) ((LayoutInflater) this
				.getSystemService("layout_inflater")).inflate(
				R.layout.dialog_person_headimg_path2, null);
		linearlayout.setMinimumWidth(10000);

		layoutparams = dialogCommon.getWindow().getAttributes();
		layoutparams.x = 0;
		layoutparams.y = -1000;
		layoutparams.gravity = 80;
		dialogCommon.onWindowAttributesChanged(layoutparams);

		dialogCommon.setCanceledOnTouchOutside(true);
		dialogCommon.setContentView(linearlayout);

		dialogCommon.findViewById(R.id.dialog_headimg_use_photo)
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialogCommon.dismiss();
						if (Environment.getExternalStorageState().equals(
								Environment.MEDIA_MOUNTED)) {
							Build bd = new Build(); 
							String model = bd.MODEL;
							if (model.contains("I939")) {
								Intent intent3 = new Intent(
										PersonInfoActivity.this,
										CustomCameraActivity.class);
								startActivityForResult(intent3,
										REQUEST_CODE_PHOTO_SUMSUNG);
							} else {
								ContentValues cv = new ContentValues();
								cv.put(MediaStore.Images.Media.MIME_TYPE,
										"image/jpeg");
								imageFileUri = getContentResolver()
										.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
												cv);
								if (imageFileUri != null) {
									Intent i = new Intent(
											android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
									i.putExtra(
											android.provider.MediaStore.EXTRA_OUTPUT,
											imageFileUri);
									i.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,
											0);
									startActivityForResult(i,
											STATE_PAIZHAO_BACK);
								} 
							}
						} else {
							Utils.showToast(instance, "SD卡不可用",
									Toast.LENGTH_SHORT);
						}
					}
				});
		dialogCommon.findViewById(R.id.dialog_headimg_use_album)
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialogCommon.dismiss();
						Intent intent = new Intent(Intent.ACTION_PICK);
						intent.setDataAndType(
								MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
								"image/jpg");
						startActivityForResult(intent, STATE_ALBUM_BACK);
					}
				});
		dialogCommon.findViewById(R.id.dialog_headimg_cancel)
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialogCommon.dismiss();
					}
				});

		dialogCommon.show();
	}

	/** 修改头像 */
	private void headImgModify() {

		if (dialogCommon != null) {
			dialogCommon = null;
		}

		final MyDialog dialogCommon = new MyDialog(this,
				R.style.dialog_headsetting);
		LinearLayout linearlayout;
		android.view.WindowManager.LayoutParams layoutparams;
		linearlayout = (LinearLayout) ((LayoutInflater) this
				.getSystemService("layout_inflater")).inflate(
				R.layout.dialog_person_headimg_path2, null);
		linearlayout.setMinimumWidth(10000);

		layoutparams = dialogCommon.getWindow().getAttributes();
		layoutparams.x = 0;
		layoutparams.y = -1000;
		layoutparams.gravity = 80;
		dialogCommon.onWindowAttributesChanged(layoutparams);

		dialogCommon.setCanceledOnTouchOutside(true);
		dialogCommon.setContentView(linearlayout);

		dialogCommon.findViewById(R.id.dialog_headimg_use_photo)
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialogCommon.dismiss();
						if (Environment.getExternalStorageState().equals(
								Environment.MEDIA_MOUNTED)) {
							ContentValues cv = new ContentValues();
							cv.put(MediaStore.Images.Media.MIME_TYPE,
									"image/jpeg");
							imageFileUri = getContentResolver()
									.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
											cv);
							if (imageFileUri != null) {
								Intent i = new Intent(
										android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
								i.putExtra(
										android.provider.MediaStore.EXTRA_OUTPUT,
										imageFileUri);
								i.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
								startActivityForResult(i, STATE_PAIZHAO);
							} else {

							}
						} else {
							Utils.showToast(instance, "SD卡不可用",
									Toast.LENGTH_SHORT);
						}
					}
				});
		dialogCommon.findViewById(R.id.dialog_headimg_use_album)
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialogCommon.dismiss();
						Intent intent = new Intent(Intent.ACTION_PICK);
						intent.setDataAndType(
								MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
								"image/jpg");
						startActivityForResult(intent, STATE_ALBUM);
					}
				});
		dialogCommon.findViewById(R.id.dialog_headimg_cancel)
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialogCommon.dismiss();
					}
				});

		// 第三方
		View sina_layout, tencent_layout;
		TextView sinaText, tecentText;
		sina_layout = dialogCommon.findViewById(R.id.dialog_headimg_use_sina);
		tencent_layout = dialogCommon.findViewById(R.id.dialog_headimg_use_qq);
		sinaText = (TextView) (dialogCommon
				.findViewById(R.id.tv_heading_use_sina));
		tecentText = (TextView) (dialogCommon
				.findViewById(R.id.tv_heading_use_qq));

		if (LoginInfo.getInstance().getBangdinglist() != null
				&& LoginInfo.getInstance().getBangdinglist().size() > 0) {

			sina_layout.setClickable(false);
			tencent_layout.setClickable(false);
			sinaText.setTextColor(0xff717171);
			tecentText.setTextColor(0xff717171);

			for (final BindInfo bindinfo : LoginInfo.getInstance()
					.getBangdinglist()) {
				if (bindinfo != null
						&& Constant.BINDING_TYPE_SINA
								.equals(bindinfo.getType())) {
					// 绑定新浪
					sina_layout.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {}
					});
					sina_layout.setClickable(true);
					sinaText.setTextColor(0xffffffff);
				}
				if (bindinfo != null
						&& Constant.BINDING_TYPE_TENCENT.equals(bindinfo
								.getType())) {
					// 绑定腾讯
					tencent_layout.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {}
					});
					tencent_layout.setClickable(true);
					tecentText.setTextColor(0xffffffff);
				}
			}

		} else {
			sina_layout.setClickable(false);
			tencent_layout.setClickable(false);
			sinaText.setTextColor(0xff717171);
			tecentText.setTextColor(0xff717171);

		}
		dialogCommon.show();

	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		// if(LoginInfo.getInstance().getLoginState() ==
		// LoginInfo.THIRDPARTY_LOGIN &&
		// !LoginInfo.getInstance().getIsuser().isIseditusername()){
//		if (isGoSetUserName()) {
//		} else {
			LoginInfo.getInstance().saveInstance(this);
//			udateUserInfoThread(detailStr, txt_sex.getText().toString(),
//					txt_area.getText().toString());
//		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == STATE_ALBUM) {
			if (data != null && data.getData() != null) {
				imageFileUri = data.getData();
				// startPicCut(data.getData(), 4);
				startPicCut(imageFileUri, STATE_CAIJIAN, STATE_ALBUM);
			}
		} else if (requestCode == STATE_PAIZHAO) {
			if (resultCode == 0) {
				return;
			}
			if (imageFileUri != null) {
				// String picPath = Utility.getPicPathFromUri(imageFileUri,
				// this);

				// startPicCut(Uri.fromFile(new File(picPath)), STATE_CAIJIAN);
				// Logger.i(TAG, "拍照返回imageFileUri != null");
				startPicCut(imageFileUri, STATE_CAIJIAN, STATE_PAIZHAO);
			} else if (data != null && data.getData() != null) {
				// Logger.i(TAG, "拍照返回imageFileUri === null");
				String picPath = Utility.getPicPathFromUri(imageFileUri, this);
				// ThumbnailUtils.autoRorate(picPath, getHeadImgFilePath());

				startPicCut(Uri.fromFile(new File(picPath)), STATE_CAIJIAN,
						STATE_PAIZHAO);
			}
		} else if (requestCode == STATE_CAIJIAN) {
			// Logger.i(TAG, "STATE_CAIJIAN返回了");
			if (data != null) {
				 Logger.i(TAG, "STATE_CAIJIAN返回了且data!=null");
				try {
					setPicToView(data);
					if (!file.exists()) {
						Toast.makeText(getApplicationContext(), "图片不存在",
								Toast.LENGTH_SHORT).show();
					} else {
						uploadImg(LoginInfo.getInstance().getLoginState(),HAND_MODIFY_STATE_HEAD);
						
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}else if (requestCode == STATE_CAIJIAN_BACK) {
			 Logger.i(TAG, "STATE_CAIJIAN_BACK返回了");
			if (data != null) {
				 Logger.i(TAG, "STATE_CAIJIAN_BACK返回了且data!=null");
				try {
					setPicToViewWithBack(data);
					if (!file.exists()) {
						Toast.makeText(getApplicationContext(), "图片不存在",
								Toast.LENGTH_SHORT).show();
					} else {
						uploadImg(LoginInfo.getInstance().getLoginState(),HAND_MODIFY_STATE_BACK);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}else if (requestCode == STATE_ALBUM_BACK) {
			if (data != null && data.getData() != null) {
				imageFileUri = data.getData();
				// startPicCut(data.getData(), 4);
				startPicCut(imageFileUri, STATE_CAIJIAN_BACK, STATE_ALBUM_BACK);
			}
		} else if (requestCode == STATE_PAIZHAO_BACK) {
			if (resultCode == 0) {
				return;
			}
			if (imageFileUri != null) {
				// String picPath = Utility.getPicPathFromUri(imageFileUri,
				// this);

				// startPicCut(Uri.fromFile(new File(picPath)), STATE_CAIJIAN);
				// Logger.i(TAG, "拍照返回imageFileUri != null");
				startPicCut(imageFileUri, STATE_CAIJIAN_BACK, STATE_PAIZHAO_BACK);
			} else if (data != null && data.getData() != null) {
				// Logger.i(TAG, "拍照返回imageFileUri === null");
				String picPath = Utility.getPicPathFromUri(imageFileUri, this);
				// ThumbnailUtils.autoRorate(picPath, getHeadImgFilePath());

				startPicCut(Uri.fromFile(new File(picPath)), STATE_CAIJIAN_BACK,
						STATE_PAIZHAO_BACK);
			}
		}else if (requestCode == HAND_AREA) {

			if (data != null) {
//				// String region = data.getStringExtra("region");
//				// txt_area.setText(region);
//				// LoginInfo.getInstance().setRegion(region);
//				String proname = data.getStringExtra("proname");
//				String cityname = data.getStringExtra("cityname");
////				txt_area.setText(proname + " " + cityname);
//				LoginInfo.getInstance().setRegion(proname + " " + cityname);
//				udateUserInfoThread(detailStr, txt_sex.getText().toString(),
//						/*txt_area.getText().toString()*/"");
			}

		} else if (requestCode == HAND_SIGN) {

			if (data != null) {
				String sign = data.getStringExtra("sign");
				setTextDetail(sign);
				LoginInfo.getInstance().setDetail(sign);
//				udateUserInfoThread(detailStr, txt_sex.getText().toString(),
//						/*txt_area.getText().toString()*/"");
				RequestEngine engine = new RequestEngine();
				engine.updataUserInfo(PersonInfoActivity.this, sign, 2);
			}
		} else if (requestCode == HAND_NICKNAME) {

			if (data != null) {
				String nickName = data.getStringExtra("nickName");
				text_nickName.setText(nickName);
				RequestEngine engine = new RequestEngine();
				engine.updataUserInfo(PersonInfoActivity.this, nickName, 0);
				LoginInfo.getInstance().setNickName(nickName);				
				LoginInfo.getInstance().saveInstance(PersonInfoActivity.this);
			}
		} else if (requestCode == REQUEST_CODE_PHOTO_SUMSUNG)
			if (resultCode == RESULT_OK) {
				if (data != null && data.getExtras() != null
						&& data.getExtras().containsKey("data")) {
					imageFileUri = data.getExtras().getParcelable("data");
					if (imageFileUri != null) {
						startPicCut(imageFileUri, STATE_CAIJIAN_BACK, STATE_PAIZHAO_BACK);
					}
				} else {
					Toast.makeText(this, "没抓取到照片~", Toast.LENGTH_SHORT).show();
				}
			}
	}
	

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case HAND_MODIFY_HEAD_SUCCESS:
				uploadSuccess = true;
//				if (checkThread != null && checkThread.isAlive()) {
//					checkThread.interrupt();
//					checkThread = null;
//				}
				if (msg.obj != null) {
					LoginInfo.getInstance().setUserImg(msg.obj.toString());
					LoginInfo.getInstance().saveInstance(
							PersonInfoActivity.this);
					Toast.makeText(PersonInfoActivity.this, "头像设置成功",
							Toast.LENGTH_SHORT).show();
				}
				// SetHead setHead = new SetHead();
				// setHead.setHead(LoginInfo.getInstance().getUserImg(),LoginInfo.getInstance().getSex(),viewHead);

				if (progDialog != null) {
					progDialog.dismiss();
				}
				progDialog = null;
				break;
			case HAND_MODIFY_HEAD_TIMEOUT:
//				if (uploadThread != null && uploadThread.isAlive()) {
//					uploadThread.interrupt();
//					uploadThread = null;
//				}
				Toast.makeText(PersonInfoActivity.this, "头像设置超时",
						Toast.LENGTH_SHORT).show();
				if (progDialog != null) {
					progDialog.dismiss();
				}
				progDialog = null;
				break;
			case HAND_MODIFY_HEAD_FAIL:
				uploadSuccess = true;
//				if (checkThread != null && checkThread.isAlive()) {
//					checkThread.interrupt();
//					checkThread = null;
//				}
				Toast.makeText(PersonInfoActivity.this, "头像设置失败",
						Toast.LENGTH_SHORT).show();
				if (progDialog != null) {
					progDialog.dismiss();
				}
				progDialog = null;
				break;
			case HAND_MODIFY_BACK_SUCCESS:
				uploadSuccess = true;
//				if (checkThread != null && checkThread.isAlive()) {
//					checkThread.interrupt();
//					checkThread = null;
//				}

				if (msg.obj != null) {
					LoginInfo.getInstance().setUserBackImg(msg.obj.toString());
					LoginInfo.getInstance().saveInstance(
							PersonInfoActivity.this);
					Toast.makeText(PersonInfoActivity.this, "背景设置成功",
							Toast.LENGTH_SHORT).show();
				}
				
				if (progDialog != null) {
					progDialog.dismiss();
				}
				progDialog = null;
				break;
			case HAND_MODIFY_BACK_TIMEOUT:
//				if (uploadThread!=null && uploadThread.isAlive()) {
//					uploadThread.interrupt();
//					uploadThread = null;
//				}
				Toast.makeText(PersonInfoActivity.this, "背景设置超时",
						Toast.LENGTH_SHORT).show();
				if (progDialog != null) {
					progDialog.dismiss();
				}
				progDialog = null;
				break;
			case HAND_MODIFY_BACK_FAIL:
				uploadSuccess = true;
//				if (checkThread!=null && checkThread.isAlive()) {
//					checkThread.interrupt();
//					checkThread = null;
//				}
				Toast.makeText(PersonInfoActivity.this, "背景设置失败",
						Toast.LENGTH_SHORT).show();
				if (progDialog != null) {
					progDialog.dismiss();
				}
				progDialog = null;
				break;
			case HAND_SEX:
				break;
			case HAND_HEAD:
				break;
			case HAND_NICKNAME:
				// 用于通知发送给服务器；
				break;
			case HAND_AREA:
				break;
			case HAND_PWD:
				break;
			case HAND_SIGN:
				break;
			case HAND_AREA_OK:
				gotoCitySelect();
				break;
			case HAND_AREA_FAIL:
				gotoCitySelect();
				break;
			}
		}

	};

	// 以下为拍照，相册处理头像所用**************************************
	/** 拍照相关的 */
	/** 图片路径 */
	// private static String imageFilaName =
	// Environment.getExternalStorageDirectory().getPath()+"/ImgCach/head.jpg";
	private static String imageFilaName = "/ImgCach/head.jpg";
	private static String imageBackFilaName = "/ImgCach/back.jpg";
	private ImageFileCache imgCacheUtil;

	private File file;

	/**
	 * 裁剪图片的方法
	 * 
	 * @param uri
	 */
	public void startPicCut(Uri uri, int resultCode, int fromState) {
		if(fromState == STATE_PAIZHAO_BACK || fromState == STATE_ALBUM_BACK){

//			String[] proj = {MediaStore.Images.Media.DATA};
//            //好像是android多媒体数据库的封装接口，具体的看Android文档
//            Cursor cursor = managedQuery(uri, proj, null, null, null); 
//            //按我个人理解 这个是获得用户选择的图片的索引值
//            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
//          //将光标移至开头 ，这个很重要，不小心很容易引起越界
//            cursor.moveToFirst();
//            //最后根据索引值获取图片路径
//            String path = cursor.getString(column_index);
//            int degree = readPictureDegree(path);
//            
//			 Intent intentCarema = new Intent("com.android.camera.action.CROP");
//			 
//			 intentCarema.setDataAndType(uri, "image/*");
//			 Logger.i(TAG, "degree=="+degree);
//			 if(degree != 0){
//				 intentCarema.setFlags(2);
//	         }
//			 intentCarema.putExtra("crop", true);
//			 intentCarema.putExtra("aspectX", 9);
//			 intentCarema.putExtra("aspectY", 5);
//			 intentCarema.putExtra("outputX", 540);
//			 intentCarema.putExtra("outputY", 300);
//			 intentCarema.putExtra("return-data", true);
//			 intentCarema.putExtra("scale", true);
//			 startActivityForResult(intentCarema, resultCode);
//			 if(cursor != null){
//				 cursor.close();
//			 }
			 Intent intentCarema = new Intent("com.android.camera.action.CROP");
			 intentCarema.setDataAndType(uri, "image/*");
			// 设置裁剪
			 intentCarema.putExtra("crop", "true");
				// aspectX aspectY 是宽高的比例
			 intentCarema.putExtra("aspectX", 1);
			 intentCarema.putExtra("aspectY", 1);
				// outputX outputY 是裁剪图片宽高
			 intentCarema.putExtra("outputX", 320);
			 intentCarema.putExtra("outputY", 320);
			 intentCarema.putExtra("return-data", true);
			 startActivityForResult(intentCarema, resultCode);
			 return;
		}
		// Intent intentCarema = new Intent("com.android.camera.action.CROP");
		// intentCarema.setDataAndType(uri, "image/*");
		// intentCarema.putExtra("crop", true);
		// if (sendImgFlag == SEND_HEAD_IMG_FLAG) {
		// intentCarema.putExtra("aspectX", 1);
		// intentCarema.putExtra("aspectY", 1);
		// intentCarema.putExtra("outputX", 160);
		// intentCarema.putExtra("outputY", 160);
		// } else if (sendImgFlag == SEND_BG_IMG_FLAG) {
		// intentCarema.putExtra("aspectX", 9);
		// intentCarema.putExtra("aspectY", 5);
		// intentCarema.putExtra("outputX", 540);
		// intentCarema.putExtra("outputY", 300);
		// }
		// intentCarema.putExtra("return-data", true);
		// intentCarema.putExtra("scale", true);
		// // intentCarema.putExtra("outputFormat", "JPEG");
//		Intent intentCarema = new Intent();
//		intentCarema.setClass(instance, PersonHeadTailorlActivity.class);
//		intentCarema.setData(uri);
//		intentCarema.putExtra(PersonHeadTailorlActivity.fromFlag, fromState);
//		intentCarema.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//		intentCarema.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//		startActivityForResult(intentCarema, resultCode);
//		 return;
		 Intent intentCarema = new Intent("com.android.camera.action.CROP");
		 intentCarema.setDataAndType(uri, "image/*");
		// 设置裁剪
		 intentCarema.putExtra("crop", "true");
			// aspectX aspectY 是宽高的比例
		 intentCarema.putExtra("aspectX", 1);
		 intentCarema.putExtra("aspectY", 1);
			// outputX outputY 是裁剪图片宽高
		 intentCarema.putExtra("outputX", 320);
		 intentCarema.putExtra("outputY", 320);
		 intentCarema.putExtra("return-data", true);
		 startActivityForResult(intentCarema, resultCode);
		// overridePendingTransition(R.anim.push_up_in,R.anim.push_down_out);
	}

	/**
	 * 保存裁剪后的图片
	 * 头像的
	 * @param picData
	 * @throws IOException
	 */
	private void setPicToView(Intent picData) throws IOException {
		// Bundle bundle = picData.getExtras();
		// Logger.i(TAG, "setPicToView执行了");
		if (picData != null) {
			// Logger.i(TAG, "picData!=null");
			// Bitmap photo = picData.getParcelableExtra("data");
//			Bitmap photo = AppContext.getHeadBitmap();
//			viewHead.setImageBitmap(Utils.toRoundBitmap(photo));
//			if (imgCacheUtil == null) {
//				imgCacheUtil = new ImageFileCache();
//			}
//			Logger.i(TAG, "setPicToView执行了。。。。。。。。。。。耶");
//			imgCacheUtil.saveBitmap(photo, imageFilaName);
			// if(photo != null){
			// photo.recycle();
			// }
			// photo = null;
			// Logger.i("TAG",
			// "保存的头像路径=="+imgCacheUtil.getImagePath(imageFilaName));
//			file = new File(imgCacheUtil.getImagePath(imageFilaName));
			
			Bundle extras = picData.getExtras();
			if (extras != null) {
				Bitmap photo = extras.getParcelable("data");
				AppContext.setHeadBitmap(photo);
				viewHead.setImageBitmap(Utils.toRoundBitmap(photo));
				if (imgCacheUtil == null) {
					imgCacheUtil = new ImageFileCache();
				}
				imgCacheUtil.saveBitmap(photo, imageFilaName);
				file = new File(imgCacheUtil.getImagePath(imageFilaName));
			}
		}
	}
	
	/**
	 * 保存裁剪后的图片
	 * 个人中心背景的
	 * @param picData
	 * @throws IOException
	 */
	private void setPicToViewWithBack(Intent picData) throws IOException {
		// Bundle bundle = picData.getExtras();
		// Logger.i(TAG, "setPicToView执行了");
		if (picData != null) {
			// Logger.i(TAG, "picData!=null");
			Bitmap photo = picData.getParcelableExtra("data");
//			Bitmap photo = AppContext.getHeadBitmap();
			if (imgCacheUtil == null) {
				imgCacheUtil = new ImageFileCache();
			}else{
				imgCacheUtil = null;
				imgCacheUtil = new ImageFileCache();
			}
			imgCacheUtil.saveBitmap(photo, imageBackFilaName);
			
			file = new File(imgCacheUtil.getImagePath(imageBackFilaName));
		}
	}

	// 上传头像相关

	private Thread uploadThread, checkThread;
	private ProgressDialog progDialog;
	private boolean uploadSuccess;

	/**
	 * 
	 * @param loginType 登录状态
	 * @param type：是头像还是背景
	 */
	private void uploadImg(int loginType,int type) {
		uploadSuccess = false;
		progDialog = ProgressDialog.show(this, null, "请稍候", true, false);
		if (loginType == LoginInfo.THIRDPARTY_LOGIN) {

		} else if (loginType == LoginInfo.LOGIN) {
			uploadPicThread(type);
		}
		checkThread(type);
	}

	private void checkThread(final int type) {

		checkThread = new Thread() {

			public void run() {
				try {
					Thread.sleep(15000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (!uploadSuccess) {
					if(type == HAND_MODIFY_STATE_HEAD){
						handler.sendEmptyMessage(HAND_MODIFY_HEAD_TIMEOUT);
					}else{
						handler.sendEmptyMessage(HAND_MODIFY_BACK_TIMEOUT);
					}
					
				}

			}

		};
		checkThread.start();

	}

	private void uploadPicThread(final int type) {

		uploadThread = new Thread() {

			public void run() {

				Message msg = new Message();
				if( type == HAND_MODIFY_STATE_HEAD){
//					String result = new NetEngine().sendUserImg(file);
					String result = new RequestEngine().sendUserImg(file,1);
					if (result == null || result.equals("")) {
						msg.what = HAND_MODIFY_HEAD_FAIL;
					} else {
						msg.what = HAND_MODIFY_HEAD_SUCCESS;
						msg.obj = result;
					}
				}else{
//					String result = new NetEngine().sendUserBackImg(file);
					String result = new RequestEngine().sendUserImg(file,2);
					if (result == null || result.equals("")) {
						msg.what = HAND_MODIFY_BACK_FAIL;
					} else {
						msg.what = HAND_MODIFY_BACK_SUCCESS;
						msg.obj = result;
					}
				}
				handler.sendMessage(msg);

			}

		};
		uploadThread.start();

	}

	// 以上为拍照，相册处理头像所用**************************************

	private TextView txt_detail;
	private String detailStr = "";

	private void setTextDetail(String detail) {

		if (detail != null && !detail.equals("")) {
			detailStr = detail;
			txt_detail.setText(detail);
//			txt_detail.setTextColor(getResources().getColor(R.color.gray_bg));
		} else {
			detailStr = "";
			txt_detail.setText("Ta很懒，什么都没说");
//			txt_detail.setTextColor(getResources().getColor(R.color.dark_gray));
		}

	}

	private void logout() {
		LoginInfo.getInstance().clear(this);
		Intent mIntent = new Intent(Constant.CLEACOOKIE);
		sendBroadcast(mIntent);
		Intent intent = new Intent(this, MainPageNewActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_SINGLE_TOP);
		intent.putExtra("tag", MainPageNewActivity.FLAG_HEADLINE);
		startActivity(intent);
		finish();
	}

	private void udateUserInfoThread(final String detail, final String sex,
			final String region) {

		new AsyncTask<Void, Void, BaseInfo>() {

			@Override
			protected BaseInfo doInBackground(Void... params) {
				// TODO Auto-generated method stub
				try {
					return new NetEngine().updateUserInfo(LoginInfo
							.getInstance().getUserId(), detail, sex, region);
				} catch (NetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return null;
			}

			@Override
			protected void onPostExecute(BaseInfo result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				if (result != null && !TextUtils.isEmpty(result.getCode())
						&& result.getCode().equals("0")) {
					// success
					// PersonInfoActivity.this.finish();
				} else {
					// fail
					Toast.makeText(PersonInfoActivity.this, "保存失败",
							Toast.LENGTH_SHORT).show();
				}
			}

		}.execute();

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#finish()
	 */
	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		
	}

	/**
	 * 判断是否设置过用户名
	 * 
	 * @author Administrator
	 * 
	 */
	private class SendDataAsync extends AsyncTask<Void, Void, Boolean> {

		private String errorMsg = "";
		IsEditUserNameInfo editInfo = null;
		public int type = 0;

		/**
         * 
         */
		public SendDataAsync(int type) {
			this.type = type;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			try {
				editInfo = new NetEngine().isEditUserName(LoginInfo
						.getInstance().getUserId());
			} catch (Exception e) {
				e.printStackTrace();
				errorMsg = e.getMessage();
			}
			return false;

		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if (pd != null && pd.isShowing()) {
				pd.cancel();
				pd = null;
			}
			if (errorMsg.equals("")) {
				isJudge = true;
				if (editInfo.getCode().equals("1")) {
					if (!editInfo.isIseditusername()) {
						// 设置过用户名
						LoginInfo.getInstance().setSetUserName(true);
						LoginInfo.getInstance().setLoginState(LoginInfo.LOGIN);
						LoginInfo.getInstance().saveInstance(
								PersonInfoActivity.this);
//						if (txtNameModity != null) {
//							txtNameModity.setVisibility(View.GONE);
//						}
						if (type == 1) {
							areaSelectShow();
						} else if (type == 2) {
							sexSelectShow();
						} else if (type == 3) {
							headImgModify();
						} else if (type == 4) {
							Intent intent = new Intent();
							intent.setClass(PersonInfoActivity.this,
									PersonSignActivity.class);
							startActivityForResult(intent, HAND_SIGN);
						} else if (type == 5) {
						} else if (type == 6) {
							Intent intentPwd = new Intent();
							intentPwd.setClass(PersonInfoActivity.this,
									PersonPwdModifyActivity.class);
							startActivity(intentPwd);
						}else if (type == 8) {
							backImgModify();
						} 
					} else {
						LoginInfo.getInstance().setSetUserName(false);
						LoginInfo.getInstance().saveInstance(
								PersonInfoActivity.this);
						if (type != 0) {
							goSetUsername();
						}
					}
				} else {
					// ToastAlone.showToast(PersonInfoActivity.this,
					// editInfo.getMsg(), 1);
				}
			} else {
				isJudge = false;
				ToastAlone.showToast(PersonInfoActivity.this, errorMsg, 1);
			}
		}
	}

	/**
	 * 传送头像数据给服务器
	 */
	private class SendHeadToServerAsync extends AsyncTask<Void, Void, Boolean> {

		private String errorMsg = "";

		private ProgressDialog pd;
		int result = -1;
		String userId = "";
		String headUrl = "";

		public SendHeadToServerAsync(String userId, String headUrl) {
			this.userId = userId;
			this.headUrl = headUrl;
			// Logger.i(TAG, "SendHeadToServerAsync执行了……。");
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pd = Utils.getProgressDialog(PersonInfoActivity.this,
					getResources().getString(R.string.get_data), this);
			pd.show();
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			try {
				NetEngine engine = new NetEngine();
				result = engine.SendHeadToServer(userId, headUrl);
			} catch (Exception e) {
				e.printStackTrace();
				errorMsg = e.getMessage();
			}
			return false;

		}

		@Override
		protected void onPostExecute(Boolean resultBool) {
			super.onPostExecute(resultBool);
			if (pd != null && pd.isShowing()) {
				pd.cancel();
			}
			if (errorMsg == null) {
				if (result == 0) {
					// Logger.i("LoginInfo", "下面执行saveInstance方法");
					LoginInfo.getInstance().saveInstance(
							PersonInfoActivity.this);
				} else {
					ToastAlone.showToast(PersonInfoActivity.this,
							"上传头像失败，请稍后重试！", 1);
				}
				return;
			} else if (errorMsg.equals("")) {
				if (result == 0) {
					// Logger.i("LoginInfo", "下面执行1111saveInstance方法");
					LoginInfo.getInstance().saveInstance(
							PersonInfoActivity.this);
				} else {
					ToastAlone.showToast(PersonInfoActivity.this,
							"上传头像失败，请稍后重试！", 1);
				}
			} else {
				ToastAlone.showToast(PersonInfoActivity.this, errorMsg, 1);
			}
		}
	}

	/**
     * 读取图片属性：旋转的角度
     * @param path 图片绝对路径
     * @return degree旋转的角度
     */
    public static int readPictureDegree(String path) {
        int degree  = 0;
        try {
                ExifInterface exifInterface = new ExifInterface(path);                
                int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
                switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                        degree = 90;
                        break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                        degree = 180;
                        break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                        degree = 270;
                        break;
                }
        } catch (IOException e) {
                e.printStackTrace();
        }
        return degree;
    }
}
